<?php
/**
 * 广告Service
 * Date: 2025/09/10
 */

namespace App\Services\Admin;

use App\Models\AdvertModel;
use App\Models\ViewModel;
use App\Services\BaseService;

class AdvertService extends BaseService
{
    /**
     * 广告列表
     * @date 2025/09/16
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function list($params)
    {
        // 查询广告内容
        $data = AdvertModel::query()
            ->select(['id', 'name', 'type', 'sort', 'status', 'created_at'])
            ->when(isset($params['name']) && $params['name'] != '', function ($query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            })
            ->when(isset($params['type']) && !empty($params['type']), function ($query) use ($params) {
                $query->where('type', $params['type']);
            })
            ->when(isset($params['status']) && !empty($params['status']), function ($query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc')
            ->paginate($params['size'] ?? config('project.size'));

        // 拼装列表其他数据
        $list = json_decode(json_encode($data->items()), true);
        if (!empty($list)) {
            $advertIds = array_column($list, 'id');
            $viewList = ViewModel::query()
                ->selectRaw('data_id, sum(pv) as view_count, count(distinct ip) AS ip_count')
                ->where('type', ViewModel::TYPE_ADVERT)
                ->whereIn('data_id', $advertIds)
                ->groupBy('data_id')
                ->get()
                ->toArray();
            $viewList = array_column($viewList, null, 'data_id');
            foreach ($list as &$item) {
                $item['view_count'] = $viewList[$item['id']]['view_count'] ?? 0;
                $item['ip_count'] = $viewList[$item['id']]['ip_count'] ?? 0;
            }
        }
        return $this->success([
            'list' => $list,
            'meta' => [
                'total' => $data->total(),
                'size'  => $data->perPage(),
                'page'  => $data->currentPage()
            ]
        ]);
    }

    /**
     * 广告创建
     * @date 2025/09/16
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function create($params)
    {
        // 广告创建
        AdvertModel::query()->create([
            'name' => $params['name'],
            'type' => $params['type'],
            'jump' => $params['jump'],
            'jump_link' => $params['jump_link'],
            'sort' => $params['sort'],
            'status' => $params['status']
        ]);
        return $this->success();
    }

    /**
     * 广告详情
     * @date 2025/09/16
     * @param int $id 广告ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        // 广告详情
        $advertInfo = AdvertModel::query()
            ->select(['id', 'name', 'type', 'jump', 'jump_link', 'sort', 'status'])
            ->where('id', $id)
            ->first();
        if (empty($advertInfo)) {
            return $this->failed('广告不存在');
        }
        return $this->success($advertInfo);
    }

    /**
     * 广告更新
     * @date 2025/09/16
     * @param array $params 请求参数
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($params)
    {
        // 检测广告
        if (!AdvertModel::query()->where('id', $params['id'])->exists()) {
            return $this->failed('广告不存在');
        }

        // 广告更新
        AdvertModel::query()->where('id', $params['id'])->update([
            'name' => $params['name'],
            'type' => $params['type'],
            'jump' => $params['jump'],
            'jump_link' => $params['jump_link'],
            'sort' => $params['sort'],
            'status' => $params['status']
        ]);
        return $this->success();
    }

    /**
     * 广告删除
     * @date 2025/09/16
     * @param int $id 广告ID
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id)
    {
        // 检测广告
        if (!AdvertModel::query()->where('id', $id)->exists()) {
            return $this->failed('广告不存在');
        }

        // 广告删除
        AdvertModel::query()->where('id', $id)->delete();
        return $this->success();
    }
}
